#include <regx51.h>
#include <stdio.h>
#include "lcd1602.h"


char OnOff = 1;
unsigned long frency = 5000; //1KHz
unsigned int timer_value = 0;

int T = 200;
int count = 0;
int duty = 10;
char flag = 0;

char buf[16] = {"                "};

void EXIT_0_ISR() interrupt 0 using 0
{
	duty += 10;
	if(duty > 200) {
			duty = 200;
	}
}
void EXIT_1_ISR() interrupt 2 using 1
{
	duty -= 10;
	if(duty < 0) {
		duty = 0;
	}
}

void TIMER_0_ISR() interrupt 1 using 2
{
	if(flag == 0x00) {
		if(count++ >= duty) {
			P1_0 = !P1_0;
			count = 0;
			flag ^= 0x01;
		}
	} else {
		if(count++ >= (T - duty)) {
			P1_0 = !P1_0;
			count = 0;
			flag ^= 0x01;
		}
	}
	TH0 = timer_value >> 8;
	TL0 = timer_value & 0x00FF;
}

void main()
{
	LCD_Init();
	EA = 1; //enable interrupt
	EX0 = 1;//enable exit 0 interrupt
	EX1 = 1;//enable exit 1 interrupt
	IT0 = 1;//edge trigger
	IT1 = 1;//edge trigger
	
	TMOD = 0x01;//timer0 16bit mode
	ET0 = 1;//enable timer 0 interrupt
	TR0 = 1;//run timer 0
	
	timer_value = 65535; 
	TH0 = (timer_value >> 8);
	TL0 = (timer_value&0x00FF);
	
	PX0 = 1;
	PX1 = 1;
	
	while(1) 
	{
		sprintf(buf, "%.2f", duty/2.0);
		LCD_Display(buf, 1, 0, 6);
		LCD_Display("%", 1, 6, 1);
	}
}